import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { computed, defineComponent, PropType, ref } from 'vue';
import { ISysMap } from '@ibiz/model-core';
import './map.scss';
import {
  MapController,
  IControlProvider,
  IMapData,
} from '@ibiz-template/runtime';
import { MapOptions } from '../../common';

const MapControl = defineComponent({
  name: 'IBizMapControl',
  props: {
    modelData: { type: Object as PropType<ISysMap>, required: true },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    provider: { type: Object as PropType<IControlProvider> },
    mdctrlActiveMode: { type: Number, default: undefined },
    loadDefault: { type: Boolean, default: true },
  },
  setup() {
    const c = useControlController((...args) => new MapController(...args));
    const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);
    const mapRef = ref();

    const mapOpts = computed<Partial<MapOptions>>(() => {
      return {
        strAreaCode: c.state.strAreaCode,
        defaultAreaCode: c.state.defaultAreaCode,
        jsonBaseUrl: c.state.jsonBaseUrl,
      };
    });

    return {
      c,
      ns,
      mapRef,
      mapOpts,
    };
  },
  render() {
    const { state } = this.c;
    return (
      <iBizControlBase controller={this.c}>
        {state.isLoaded && (
          <iBizMapChart
            areaData={state.areaData}
            pointData={state.pointData}
            options={this.mapOpts}
            class={this.ns.e('map')}
            onMapChange={(e: IData) => {
              this.c.onMapChange(e.areaCode);
            }}
            onPointChange={(e: IMapData) => {
              this.c.onAreaClick(e);
            }}
            onAreaChange={(e: IMapData) => {
              this.c.onPointClick(e);
            }}
          ></iBizMapChart>
        )}
      </iBizControlBase>
    );
  },
});

export default MapControl;
